#include "music.h"

#include <QUuid>
#include <QMediaPlayer>
#include <QCoreApplication>

Music::Music()
{

}

Music::Music(const QUrl& url)
    :isLike(false)
    ,isHistory(false)
    ,musicUrl(url)
{
    this->musicId = QUuid::createUuid().toString();
    parseMediaMetaMusic();
}

void Music::setMusicId(const QString &musicId)
{
    this->musicId = musicId;
}

void Music::setMusicName(const QString &musicName)
{
    this->musicName = musicName;
}

void Music::setMusicSinger(const QString& musicSinger)
{
    this->musicSinger = musicSinger;
}

void Music::setMusicAlbum(const QString& musicAlbum)
{
    this->musicAlbum = musicAlbum;
}

void Music::setDuration(qint64 duration)
{
    this->duration = duration;
}

void Music::setIsLike(bool isLike)
{
    this->isLike = isLike;
}

void Music::setIsHistory(bool isHistory)
{
    this->isHistory = isHistory;
}

void Music::setMusicUrl(QUrl musicUrl)
{
    Music::musicUrl = musicUrl;
}

QString Music::getMusicName() const
{
    return musicName;
}

QString Music::getMusicSinger() const
{
    return musicSinger;
}

QString Music::getMusicAlbum() const
{
    return musicAlbum;
}

qint64 Music::getDuration() const
{
    return duration;
}

bool Music::getIsLike() const
{
    return isLike;
}

bool Music::getIsHistory() const
{
    return isHistory;
}

QUrl Music::getMusicUrl() const
{
    return musicUrl;
}

QString Music::getMusicId() const
{
    return musicId;
}

QString Music::getLrcFilePath() const
{
    QString musicPath = musicUrl.toLocalFile();
    musicPath.replace("mp3", "lrc");
    musicPath.replace("mpga", "lrc");
    musicPath.replace("flac", "lrc");

    return musicPath;
}

void Music::insertToDB()
{
    QSqlQuery query;
    query.prepare("SELECT EXISTS (SELECT 1 FROM musicInfo WHERE musicId = ?)");
    query.addBindValue(musicId);

    if(!query.exec())
    {
        qDebug() << "查询失败！" << query.lastError().text();
        return;
    }

    while(query.next())
    {
        bool isExist = query.value(0).toBool();
        if(isExist)
        {
            //歌曲已经存在，更新 isLike 和 isHistory 属性
            query.prepare("UPDATE musicInfo SET isLike = ?, isHistory = ? WHERE musicId = ?");
            query.addBindValue(isLike ? 1 : 0);
            query.addBindValue(isHistory ? 1 : 0);
            query.addBindValue(musicId);
            if(!query.exec())
            {
                qDebug() << "更新失败：" << query.lastError().text();
                return;
            }
            qDebug() << "更新歌曲信息：" << musicId << musicName;
        }
        else
        {
            //歌曲不存在，直接插入表中
            query.prepare("INSERT INTO musicInfo(musicId, musicName, musicSinger, musicAlbum, \
                          musicUrl, duration, isLike, isHistory) \
                          VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
            query.addBindValue(musicId);
            query.addBindValue(musicName);
            query.addBindValue(musicSinger);
            query.addBindValue(musicAlbum);
            query.addBindValue(musicUrl.toLocalFile());
            query.addBindValue(duration);
            query.addBindValue(isLike ? 1 : 0);
            query.addBindValue(isHistory ? 1 : 0);
            if(!query.exec())
            {
                   qDebug() << "更新失败：" << query.lastError().text();
                   return;
            }
            qDebug() << "更新歌曲信息：" << musicId << musicName;
        }
    }
}

void Music::parseMediaMetaMusic()
{
    //1.创建媒体播放源对象
    QMediaPlayer player;

    //2.设置媒体源，依靠 setMedia 方法解析元数据
    player.setMedia(musicUrl);

    //3.由于 setMedia 不会等待歌曲加载结束，因此通过 metaMedia 获取数据时，需要通过
    //isMetaDataAvailable 检测媒体是否已经加载完毕，数据是否有效
    while(!player.isMetaDataAvailable())
    {
        QCoreApplication::processEvents();
    }

    //4.加载完成，可以获取数据
    if(player.isMetaDataAvailable())
    {
        musicName = player.metaData("Title").toString();
        musicSinger = player.metaData("Author").toString();
        musicAlbum = player.metaData("AlbumTitle").toString();
        duration = player.metaData("Duration").toLongLong();

        QString fileName = musicUrl.fileName();

        int index = fileName.indexOf('-');

        //获取不到 musicName
        if(musicName.isEmpty())
        {
            if(index != -1)
            {
                musicName = fileName.mid(0, index).trimmed();
            }
            else musicName = fileName.mid(0, fileName.indexOf('.')).trimmed();
        }

        //获取不到 musicSinger
        if(musicSinger.isEmpty())
        {
            if(index != -1)
            {
                musicSinger = fileName.mid(index + 1, fileName.indexOf('.') - index - 1).trimmed();
            }
            else musicSinger = "未知歌手";
        }

        //获取不到 musicAlbum
        if(musicAlbum.isEmpty())
        {
            musicAlbum = "未知专辑";
        }
    }
}
